package com.mj.mes.config.AopConfig;

import com.mj.mes.system.SysLogger.SysLogger;
import com.mj.mes.system.SysLogger.SysLoggerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

/**
 * author : cRyann
 *
 * @create 2017-09-08
 **/
@Aspect
@Order(1)
@Component
public class LogAopConfig {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SysLoggerService sysLoggerService;

    @Pointcut("execution(* com.mj.mes..*Service.*(..))" +
            "&&!execution(* com.mj.mes..*Service.find*(..))" +
            "&&!execution(* com.mj.mes..*Logger*.*(..))")
    public void pointCut(){

    }
//    @Before("pointCut()")
//    public void doBefore(JoinPoint joinPoint){
//
//    }
//    @Around("pointCut()")
//    public void doAround(){
//
//    }
    @After("pointCut()")
    public void doAfter(JoinPoint joinPoint) {
        // 处理完请求，返回内容
        logger.info("Service Action:" + joinPoint.getSignature().getName() + ":" + Arrays.toString(joinPoint.getArgs()));
        StringBuffer modifyContent = new StringBuffer();
        modifyContent.append(joinPoint.getSignature().getName());
        modifyContent.append(Arrays.toString(joinPoint.getArgs()));
        try {
            String currentUser = (String) SecurityUtils.getSubject().getPrincipal();
            if (null != currentUser && !"".equals(currentUser)) {
                SysLogger sysLogger = new SysLogger();
                sysLogger.setModifyTime(new Date());
                sysLogger.setUserName(currentUser);
                sysLogger.setModifyContent(modifyContent.toString());
                sysLoggerService.addSysLogger(sysLogger);
            }
        }catch (UnavailableSecurityManagerException e){
            //todo shiro异常，未处理 只捕捉
            /* org.apache.shiro.UnavailableSecurityManagerException:
             No SecurityManager accessible to the calling code,
             either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton.
             This is an invalid application configuration.
            */
            //e.printStackTrace();
            SysLogger sysLogger = new SysLogger();
            sysLogger.setModifyTime(new Date());
            sysLogger.setUserName("System");
            sysLogger.setModifyContent(modifyContent.toString());
            sysLoggerService.addSysLogger(sysLogger);
        }

    }
}
